package io.gitee.zhucan123.core.rest;

import com.niimbot.middlend.core.infrastructure.util.RestMultiData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.net.URI;

/**
 * @author: zhuCan
 * @date: 2020/2/24 15:03
 * @description:
 */
@Component
public abstract class RestClient {

  @Autowired
  private RestTemplate restTemplate;

  /**
   * 获取host
   *
   * @return
   */
  protected abstract String host();

  /**
   * 执行请求
   *
   * @param api
   * @param entity
   * @param returnType
   * @param <R>
   * @return
   */
  public <R> ResponseEntity<R> exchange(RestApi api,
                                        HttpEntity<?> entity,
                                        Class<R> returnType) {
    return restTemplate.exchange(URI.create(host() + api.url()), api.method(), entity, returnType);
  }

  /**
   * 构建httpEntity
   *
   * @param param
   * @param httpHeaders
   * @return
   */
  public HttpEntity<MultiValueMap> createHttpEntity(Object param, HttpHeaders httpHeaders) {
    return new HttpEntity<>(RestMultiData.multiValueMap(param), httpHeaders);
  }
}
